<?php

namespace app\common\model;

use think\Model;

class ScoreLog extends Model
{
    // 自动时间戳
    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'create_time';

    // 类型映射（可扩展）
    const TYPE_SIGN = 'sign';          // 签到
    const TYPE_INVITE = 'invite';      // 邀请好友
    const TYPE_SHOPPING = 'shopping';  // 购物返利
    const TYPE_EXCHANGE = 'exchange';  // 积分兑换
    const TYPE_FAKE = 'fake';  // 卡密兑换
    const TYPE_ADMIN = 'admin';        // 管理员操作

    /**
     * 获取类型映射
     * @return array
     */
    public static function getTypes()
    {
        return [
            self::TYPE_SIGN     => '每日签到',
            self::TYPE_INVITE   => '邀请奖励',
            self::TYPE_SHOPPING => '购物返利',
            self::TYPE_EXCHANGE => '积分兑换',
            self::TYPE_ADMIN    => '管理员调整',
        ];
    }

    /**
     * 获取用户积分明细
     * @param int $userId
     * @param int $page
     * @param int $pageSize
     * @return \think\Paginator
     */
    public static function getUserLogs($userId, $page = 1, $pageSize = 15)
    {
        return self::where('user_id', $userId)
            ->field('id,score,type,scene,remark,create_time')
            ->order('id DESC')
            ->paginate([
                'page' => $page,
                'list_rows' => $pageSize,
            ]);
    }

    /**
     * 添加日志（通过服务类调用，不建议直接使用）
     * @param array $data
     * @return bool
     */
    public static function addLog($data)
    {
        $default = [
            'user_id' => 0,
            'score' => 0,
            'type' => '',
            'scene' => '',
            'remark' => '',
            'extra' => null
        ];
        return self::create(array_merge($default, $data));
    }
}
